import { Injectable } from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild,
  NavigationExtras,
  CanLoad, Route
} from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    let url: string = state.url;
    console.log('路由守卫进入', url);
    // return true;
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

  canLoad(route: Route): boolean {  // 用于路由的懒加载
    let url = `/${route.path}`;
    console.log('守卫加载1', url);
    // this.router.navigate(['crisis-center']);
    // return false;
    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {  //保护他防止未授权访问
    if (this.authService.isLoggedIn) {
      console.log('已登录');
      return true;
    } else {
      console.log('未登录');
    }

    // 存路由
    this.authService.redirectUrl = url;

    // Create a dummy session id
    let sessionId = 123456789;

    // Set our navigation extras object
    // that contains our global query params and fragment
    let navigationExtras: NavigationExtras = {
      queryParams: { 'session_id': sessionId },
      fragment: 'anchor'
    };

    // Navigate to the login page with extras
    this.router.navigate(['./login'], navigationExtras);
    // this.router.navigate(['./admin']);
    return false;
  }
}
